package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.BaseParamBo;
import com.cskaoyan.bean.BaseRespData;
import com.cskaoyan.bean.admin.other.AdminLoginInfoVo;
import com.cskaoyan.bean.admin.other.DashBoardVo;
import com.cskaoyan.bean.admin.other.InfoDataVo;
import com.cskaoyan.bean.pojo.Admin;
import com.cskaoyan.bean.pojo.AdminExample;
import com.cskaoyan.bean.admin.system.*;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.service.admin.AdminService;
import com.cskaoyan.util.Md5utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public BaseRespData query(String username, BaseParamBo param) {

        //开启分页功能
        PageHelper.startPage(param.getPage(),param.getLimit());

        //拼接分页排序
        AdminExample adminExample = new AdminExample();
        adminExample.setOrderByClause(param.getSort()+ " " +param.getOrder());

        AdminExample.Criteria criteria = adminExample.createCriteria();

        if(username != null && !"".equals(username)){
            criteria.andUsernameLike("%"+username+"%");
        }
        criteria.andDeletedEqualTo(false);

        List<Admin> admins = adminMapper.selectByExample(adminExample);
        ArrayList<ListAdminsVo> listAdminsVos = new ArrayList<>();
        for (Admin admin : admins) {
            ListAdminsVo listAdminsVo = new ListAdminsVo(admin.getId(),admin.getUsername(),admin.getAvatar(),admin.getRoleIds());
            listAdminsVos.add(listAdminsVo);
        }

        PageInfo<Admin> adminPageInfo = new PageInfo<>(admins);
        long total = adminPageInfo.getTotal();

        return BaseRespData.create(listAdminsVos,total);
    }

    @Override
    public int delete(ListAdminsVo adminsVo) {

        //实际执行的是修改
        int affectedRows = adminMapper.deleteById(adminsVo.getId());

        if(affectedRows == 0){
            return 404;
        }
        return 200;
    }

    @SneakyThrows
    @Override
    public ModifyAdminsVo update(ModifyAdminsBo modifyAdminsBo) {

        //先查旧密码
        Admin adminInfo = adminMapper.selectByPrimaryKey(modifyAdminsBo.getId());
        String oldPassword = adminInfo.getPassword();

//        //新旧密码相同
//        if(oldPassword.equals(modifyAdminsBo.getPassword())){
//            return null;
//        }

        //获取当前时间date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date datetime = sdf.parse(sdf.format(new Date()));
        String format = sdf.format(datetime);

        Admin admin = new Admin();
        admin.setId(modifyAdminsBo.getId());
        admin.setUsername(modifyAdminsBo.getUsername());
        admin.setPassword(Md5utils.getMd5Result(modifyAdminsBo.getPassword()));
        admin.setAvatar(modifyAdminsBo.getAvatar());
        admin.setRoleIds(modifyAdminsBo.getRoleIds());
        admin.setUpdateTime(datetime);
        int affectedRows = adminMapper.updateByPrimaryKeySelective(admin);

        ModifyAdminsVo modifyAdminsVo = new ModifyAdminsVo(modifyAdminsBo.getId(),modifyAdminsBo.getUsername(),Md5utils.getMd5Result(oldPassword),modifyAdminsBo.getAvatar(),format,modifyAdminsBo.getRoleIds());

        return modifyAdminsVo;
    }

    @SneakyThrows
    @Override
    public AddAdminsVo createAdmin(AddAdminsBo addAdminsBo) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(sdf.format(new Date()));

        Admin admin = new Admin();
        admin.setId(null);
        admin.setUsername(addAdminsBo.getUsername());
        admin.setPassword(Md5utils.getMd5Result(addAdminsBo.getPassword()));
        admin.setAvatar(addAdminsBo.getAvatar());
        admin.setAddTime(addTime);
        admin.setUpdateTime(addTime);
        admin.setDeleted(false);
        admin.setRoleIds(addAdminsBo.getRoleIds());
        int affectedRows = adminMapper.insert(admin);

        //获得自增主键的值
        Integer id = admin.getId();
        Admin insertedAdmin = adminMapper.selectByPrimaryKey(id);

        return new AddAdminsVo(id,addAdminsBo.getUsername(),Md5utils.getMd5Result(addAdminsBo.getPassword()),addAdminsBo.getAvatar(),sdf.format(addTime),sdf.format(addTime),addAdminsBo.getRoleIds());
    }

    /**
     * 判断修改时用户名是否重复
     */
    @Override
    public Boolean usernameIsDuplicate(ModifyAdminsBo modifyAdminsBo) {

        //允许仅修改用户名之外的其他部分  所以需要先查一下当前username
        Admin currentAdmin = adminMapper.selectByPrimaryKey(modifyAdminsBo.getId());

        List<String> adminNames = adminMapper.selectAdminNameList();
        for (String adminName : adminNames) {
            if(adminName.equals(modifyAdminsBo.getUsername()) && !modifyAdminsBo.getUsername().equals(currentAdmin.getUsername())){
                return true;
            }
        }

        return false;
    }

    /**
     * 判断新增时用户名是否重复
     */
    @Override
    public Boolean usernameIsDuplicate(AddAdminsBo adminsBo) {

        List<String> adminNames = adminMapper.selectAdminNameList();
        for (String adminName : adminNames) {
            if(adminName.equals(adminsBo.getUsername())){
                return true;
            }
        }

        return false;
    }

    @Override
    public AdminLoginInfoVo selectInfo(String username,String ip) {

//        //1 首先根据用户名查询
////        Admin admin = adminMapper.selectInfo(username);
////
////        String avatar = admin.getAvatar();
////        Integer[] roleIds = admin.getRoleIds();
////        //根据roles表查询roleIds对应的name
////        ArrayList<String> roleNames = new ArrayList<>();
////        //根据permission表查询roleIds对应的permissions
////        ArrayList<String> rolePermissions = new ArrayList<>();
////        for (Integer roleId : roleIds) {
////            String roleName = adminMapper.selectRoleNameById(roleId);
////            List<String> rolePerm = adminMapper.selectPermsByRoleId(roleId);
////            roleNames.add(roleName);
////            rolePermissions.addAll(rolePerm);
////        }
////
////        InfoDataVo dataVo = new InfoDataVo();
////        dataVo.setAvatar(avatar);
////        dataVo.setName(username);
////        dataVo.setPerms(rolePermissions);
////        dataVo.setRoles(roleNames);
////        return dataVo;
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        Admin admin = adminMapper.selectByExample(adminExample).get(0);
        Date date = new Date();
        admin.setLastLoginTime(date);
        admin.setLastLoginIp(ip);
        adminMapper.updateByExampleSelective(admin,adminExample);
        Integer[] roleIds = admin.getRoleIds();
        List<String> roles=new ArrayList<>();
        List<String> perms=new ArrayList<>();
        for (Integer roleId : roleIds) {
            String name = roleMapper.selectNameById(roleId);
            List<String> list = permissionMapper.selectPermsByRoleId(roleId);
            roles.add(name);
            perms.addAll(list);
        }

        List<String> apiList = new ArrayList<>();
        for (String perm : perms) {
            if ("*".equals(perm)) {
                apiList = new ArrayList<>();
                apiList.add("*");
                break;
            }
            String api = permissionMapper.selectApiByPerm(perm);
            apiList.add(api);
        }

        AdminLoginInfoVo adminLoginInfoVo = new AdminLoginInfoVo(admin.getUsername(), admin.getAvatar(), roles, apiList);
        return adminLoginInfoVo;
    }

    @Override
    public DashBoardVo queryCount() {

        Integer goodsTotal = adminMapper.selectGoodsTotal();
        Integer userTotal = adminMapper.selectUserTotal();
        Integer productTotal = adminMapper.selectproductTotal();
        Integer orderTotal = adminMapper.selectorderTotal();

        DashBoardVo dashBoardVo = new DashBoardVo();
        dashBoardVo.setGoodsTotal(goodsTotal);
        dashBoardVo.setUserTotal(userTotal);
        dashBoardVo.setProductTotal(productTotal);
        dashBoardVo.setOrderTotal(orderTotal);
        return dashBoardVo;
    }
}
